<template>
  <div class="tcmProblemtab">
    <el-card>
      <div class="tcmProblem-add-button"><el-button type="primary" size="small" @click="handleAddTcmProblem">添加</el-button></div>
      <el-tabs v-model="activeTab">
        <!-- :cell-style="{ textAlign: 'center' }" -->
        <el-tab-pane label="酸轧单元早会问题清单" name="tcmProblem">
          <div class="tcmProblem">
            <el-table
              :data="tcmProblemData"
              :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
              size="small"
              show-overflow-tooltip
            >
              <el-table-column type="index" label="序号" width="80" fixed="left" align="center" />
              <el-table-column prop="submissionTime" label="提出时间" align="center" />
              <el-table-column prop="responsibleParty" label="责任人" align="center" />
              <el-table-column prop="problem" label="问题" width="320" align="left" />
              <el-table-column prop="estResoTime" label="计划解决时间" align="center" />
              <el-table-column prop="eqpFeedback" label="设备反馈" width="320" align="left" />
              <el-table-column prop="collaborate" label="需生产配合内容" width="320" align="left" />
              <el-table-column prop="completeStatus" label="完成状态" align="center" />
              <el-table-column prop="status" label="当前状态" align="center">
                <template #default="scope">
                  <span v-if="scope.row.status === '超时'"><el-tag type="danger">超时</el-tag></span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160" fixed="right">
                <template #default="scope">
                  <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="danger" link  @click="handleStatus(scope.row)">解决</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="历史清单" name="historyProblem">
          <div class="tcmProblem">
            <el-table
              :data="tcmProblemData"
              :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
              size="small"
              show-overflow-tooltip
            >
              <el-table-column type="index" label="序号" width="80" fixed="left" align="center" />
              <el-table-column prop="submissionTime" label="提出时间" align="center" />
              <el-table-column prop="responsibleParty" label="责任人" align="center" />
              <el-table-column prop="problem" label="问题" width="320" align="left" />
              <el-table-column prop="estResoTime" label="计划解决时间" align="center" />
              <el-table-column prop="eqpFeedback" label="设备反馈" align="left" />
              <el-table-column prop="collaborate" label="需生产配合内容" width="320" align="left" />
              <el-table-column prop="completeStatus" label="完成状态" align="center" />
              <el-table-column prop="status" label="当前状态" align="center">
                <template #default="scope">
                  <span v-if="scope.row.status === '超时'"><el-tag type="danger">超时</el-tag></span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <div class="common-div-card pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>
  </div>

  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
    <el-form :model="dialogForm" label-width="120px" :rules="rules" ref="ruleForm">
      <el-form-item label="提出时间" prop="submissionTime">
        <el-date-picker v-model="dialogForm.submissionTime" type="date" placeholder="日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="责任人" prop="responsibleParty">
        <el-input v-model="dialogForm.responsibleParty"></el-input>
      </el-form-item>
      <el-form-item label="问题" prop="problem">
        <el-input v-model="dialogForm.problem"></el-input>
      </el-form-item>
      <el-form-item label="计划解决时间" prop="estResoTime">
        <el-date-picker v-model="dialogForm.estResoTime" type="date" placeholder="日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="设备反馈" prop="eqpFeedback">
        <el-input v-model="dialogForm.eqpFeedback"></el-input>
      </el-form-item>
      <el-form-item label="需生产配合内容" prop="collaborate">
        <el-input v-model="dialogForm.collaborate"></el-input>
      </el-form-item>
      <el-form-item label="完成状态" prop="completeStatus">
        <el-select v-model="dialogForm.completeStatus" placeholder="请选择" clearable>
          <el-option label="请选择" value="" />
          <el-option label="已完成" value="已完成" />
          <el-option label="未完成" value="未完成" />
          <el-option label="待备件" value="待备件" />
          <el-option label="待研究" value="待研究" />
          <el-option label="紧急" value="紧急" />
          <el-option label="特急" value="特急" />
          <el-option label="一般" value="一般" />
          <el-option label="不急" value="不急" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive, watch } from 'vue';
  import { overviewApi } from '/@/api/report/overview';
  import { ElMessage, FormInstance, ElMessageBox } from 'element-plus';

  const activeTab = ref('tcmProblem');
  const currentMonth = ref(`${new Date().getFullYear()}年${new Date().getMonth() + 1}月`);
  const tcmProblemData = ref<any>([]);
  const dialogVisible = ref(false);
  const dialogTitle = ref('添加');
  const ruleForm = ref<FormInstance | null>(null);
  const dialogForm = ref({
    id: 0,
    submissionTime: '',
    responsibleParty: '',
    problem: '',
    estResoTime: '',
    eqpFeedback: '',
    collaborate: '',
    completeStatus: '',
    status: '',
  });
  const completeStatus='未完成';

  // 根据当前Tab获取应查询的完成状态
  const getCurrentStatus = () => (activeTab.value === 'historyProblem' ? '已完成' : '未完成');

  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  });
  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    pagination.currentPage = 1; // Reset to first page
    fetchTableData(getCurrentStatus());
  };

  // 页码变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData(getCurrentStatus());
  };

  // 添加
  const handleAddTcmProblem = () => {
    dialogTitle.value = '添加';
    dialogVisible.value = true;
    dialogForm.value = {
      id: 0,
      submissionTime: '',
      responsibleParty: '',
      problem: '',
      estResoTime: '',
      eqpFeedback: '',
      collaborate: '',
      completeStatus: '',
      status: '',
    };
  };

  const rules = ref({
    submissionTime: [{ required: true, message: '请输入提出时间', trigger: 'change' }],
    estResoTime: [{ required: true, message: '请输入计划解决时间', trigger: 'change' }],
    responsibleParty: [{ required: true, message: '请输入责任人', trigger: 'blur' }],
    problem: [{ required: true, message: '请输入问题', trigger: 'blur' }],
    completeStatus: [{ required: true, message: '请选择完成状态', trigger: 'change' }],
  });

  // 编辑
  const handleEdit = (row: any) => {
    dialogTitle.value = '编辑';
    dialogVisible.value = true;
    dialogForm.value = { ...row };
  };

  const handleStatus = async(row: any) => {
    row.completeStatus='已完成';
    const param = { ...row };
    let res = await overviewApi.problemEdit(param);
    if (res.data.status != 2000) {
      throw new Error('接口调用失败：' + res.data.msg);
    }
    ElMessage.success(`${dialogTitle.value}成功`);

  };


  // 删除
  const handleDelete = async (row: any) => {
    // 添加确认对话框
    ElMessageBox.confirm('确定要删除这条记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res = await overviewApi.problemDelete(row.id);
          if (res.data.status != 2000) {
            throw new Error('接口调用失败：' + res.data.msg);
          }
          ElMessage.success('删除成功');
          fetchTableData(getCurrentStatus);
        } catch (err) {
          console.log('获取问题清单数据失败：' + err);
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
  };

  const handleSave = async () => {
    if (ruleForm.value) {
      await ruleForm.value.validate(async (valid) => {
        if (valid) {
          try {
            let res;
            const param = { ...dialogForm.value };
            if (dialogTitle.value === '添加') {
              res = await overviewApi.problemAdd(param);
            } else {
              res = await overviewApi.problemEdit(param);
            }
            if (res.data.status != 2000) {
              throw new Error('接口调用失败：' + res.data.msg);
            }
            ElMessage.success(`${dialogTitle.value}成功`);
          } catch (err) {
            console.log('获取问题清单数据失败：' + err);
          } finally {
            dialogVisible.value = false;
            fetchTableData(getCurrentStatus());
          }
        } else {
          console.log('表单验证失败');
        }
      });
    }
  };

  const fetchTableData = async (completeStatus:any) => {
    try {
      const param = {
        page: {
          pageIndex: pagination.currentPage,
          pageSize: pagination.pageSize,
        },
        dto: {
          completeStatus:completeStatus
        },
      };
      const res = await overviewApi.problemList(param);
      if (res.data.status != 2000) {
        throw new Error('接口调用失败：' + res.data.msg);
      }
      // TODO: 处理接口返回数据
      tcmProblemData.value = res.data.data;
      pagination.total = res.data.count;
    } catch (err) {
      console.log('获取问题清单数据失败：' + err);
    }
  };

  // 监听Tab切换，动态切换查询状态
  watch(activeTab, () => {
    pagination.currentPage = 1;
    fetchTableData(getCurrentStatus());
  });

  onMounted(() => {
    fetchTableData(getCurrentStatus());
  });
</script>
<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  @box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
  @border:1px solid #dcdfe6;

  .common-div-card {
    box-shadow: @box-shadow;
    transition: 0.3s;
    border-radius: @border-radius;
    border: @border;

    // 悬停状态
    &:hover {
      box-shadow: @box-shadow-hover;
    }
  }

  .tcmProblemtab {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin: 0 1vw;
    margin-bottom: 1vh;
  }

  .tcmProblem-add-button {
    right: 2vw;
    position: absolute;
    z-index: 10;
  }

  .tcmProblem {
    .el-table {
      width: 100%;
      overflow-x: hidden;
      min-height: 40vh;
    }
  }

  .pagination {
    width: 100%;
    height: 6vh;
    display: flex;
    justify-content: flex-end;
    padding: 20px;
    margin-top: 1vh;
  }
</style>
